package me.gavin.util

import android.content.Context
import android.os.Build
import android.view.Gravity
import android.widget.TextView
import android.widget.Toast
import androidx.core.view.setPadding
import me.gavin.databinding.WidgetToastTempBinding
import me.gavin.R
import me.gavin.base.Gavin
import me.gavin.base.getColorStateListCompat

fun String.toastDone() {
    this.toast(R.drawable.default_toast_done)
}

fun String.toastError() {
    this.toast(R.drawable.default_toast_error)
}

fun String.toast(icon: Int? = null) {
    Gavin.currentActivity?.get()?.let {
        if (icon == null) {
            TextView(it).apply {
                setPadding(12f.dp2px())
                setBackgroundResource(R.drawable.shape_rect_solid_06)
                backgroundTintList = it.getColorStateListCompat(R.color.colorToast)
                gravity = Gravity.CENTER_HORIZONTAL
                text = this@toast
                textSize = 16f
                setTextColor(0xffffffff.toInt())
            }
        } else {
            WidgetToastTempBinding.inflate(it.layoutInflater).apply {
                imageView.setImageResource(icon)
                textView.text = this@toast
            }.root
        }
    }?.let {
        it.context.toast.apply {
            setGravity(Gravity.CENTER, 0, 0)
            duration = Toast.LENGTH_SHORT
            view = it
        }
    }?.show()
}

private val Context.toast get() = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) Toast(this) else sToast

private val sToast by lazy { Toast(Gavin.app) }